package com.tim.javaApi.concurrent;


import java.util.concurrent.*;
/**
 *@describe 线程协调类
 *@author Tim
 *@create 2022/8/25 17:13
 */
public class ThreadCoordinateDemo {
	
	public void semaphore() throws InterruptedException {
		int threadNum = 50;
		ExecutorService executorService = Executors.newFixedThreadPool(threadNum);
		Semaphore semaphore = new Semaphore(threadNum);
		semaphore.acquire();
		executorService.submit(()->{
			try {
				Thread.sleep(2000);
				System.out.println(1);
			} catch (Exception e) {
				e.printStackTrace();
			}finally {
				semaphore.release();
				System.out.println(2);
			}
		});
		System.out.println(3);
//		semaphore.acquire(threadNum);
//		System.out.println(4);
	}

	
	public void countdownLatch() throws InterruptedException {
		ExecutorService executorService = Executors.newFixedThreadPool(6);
		CountDownLatch countDownLatch = new CountDownLatch(3);
		for (int i = 0; i < 12; i++) {
			executorService.submit(()->{
				try {
					TimeUnit.SECONDS.sleep(2);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}finally {
					countDownLatch.countDown();
					System.out.println(Thread.currentThread().getName()+"，"+System.currentTimeMillis());
					try {
						countDownLatch.await();
						System.out.println(Thread.currentThread().getName()+"，AWAIT "+System.currentTimeMillis());
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			});
		}
		countDownLatch.await();// 等待子线程执行完毕
		System.out.println("countdownLatch over "+System.currentTimeMillis());
	}


	
	public void cyclicBarrier() throws InterruptedException {
		CyclicBarrier barrier = new CyclicBarrier(3, new HorseRace());
		for(int i = 0; i < 6; i++) {
			Horse horse = new Horse(barrier);
			HorseRace.horses.add(horse);
			HorseRace.exec.execute(horse);
		}
		while(!HorseRace.exec.isShutdown()){

		}
		System.out.println("cyclicBarrier over");
	}

}

